import React from 'react';
import { IMouseEvent } from '../../../interface';
import style from './style.module.less';

type TChild = JSX.Element | null;

interface IPage {
  Child: React.ComponentClass<any>;
  item: (active: boolean) => JSX.Element | JSX.Element[] | string | number;
}

interface IProps {
  page: IPage[];
  tabBarKey: number;
  setTabBarKey: (key: number) => void;
  transition?: boolean;
  hide?: boolean;
}

interface IState {
  child: TChild[];
}

export default class TabBar extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    const { page, tabBarKey } = this.props;
    const child: TChild[] = page.map(() => null);
    const Child = page[tabBarKey].Child;
    child[tabBarKey] = <Child />;
    this.state = {
      child,
    };
  }

  componentWillUpdate(nextProps: IProps) {
    const { page, tabBarKey } = nextProps;
    const child = this.state.child;
    if (!child[tabBarKey]) {
      const Child = page[tabBarKey].Child;
      child[tabBarKey] = <Child />;
      this.setState({
        child,
      });
    }
  }

  click = (e: IMouseEvent) => {
    this.props.setTabBarKey(+e.currentTarget.dataset.key);
  };

  render() {
    const { page, tabBarKey, transition = false, hide = false } = this.props;
    return (
      <div className="page">
        <div className="box-fill">
          <div
            className={`${style.child}${transition ? ' transition' : ''}`}
            style={{ width: `${page.length * 100}%`, left: `-${tabBarKey * 100}%` }}
          >
            {this.state.child.map((i, k) => (
              <div key={k} className={style.item}>
                {i}
              </div>
            ))}
          </div>
        </div>
        <div className={`transition ${style.tabBar} ${style[hide ? 'hide' : 'show']}`}>
          {page.map((i, k) => (
            <div key={k} className={style.item} data-key={k} onClick={this.click}>
              {i.item(tabBarKey === k)}
            </div>
          ))}
        </div>
      </div>
    );
  }
}
